<template>
  <div class="cart-container">
    <div class="header">
      <Header /> 
    </div>
    <el-card class="cart-card">
      <div class="cart-content">
        <h2 class="cart-title">购物车</h2>

        <div v-if="cartStore.cartList.length === 0" class="empty-cart">
          <el-empty description="您的购物车是空的，快去添加商品吧~"></el-empty>
          <el-button 
            type="primary" 
            @click="$router.push('/home')"
            class="go-shopping-btn"
          >
            去购物
          </el-button>
        </div>

        <!-- 购物车有商品 -->
        <el-table 
          v-else 
          :data="cartStore.cartList" 
          border 
          class="cart-table"
        >
          <!-- 商品名称 -->
          <el-table-column 
            prop="goods_desc" 
            label="商品" 
            width="400"
          />

          <!-- 单价 -->
          <el-table-column 
            prop="goods_price" 
            label="单价" 
            align="center"
          >
            <template #default="scope">
              ¥{{ scope.row.goods_price.toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 数量（带加减按钮） -->
          <el-table-column label="数量" align="center">
            <template #default="scope">
              <div class="quantity-box">
                <button class="quantity-btn" :class="{ disabled: scope.row.car_num <= 1 }" @click="handleDecrement(scope.row)">
                  - </button>
                  <span class="quantity-value">{{ scope.row.car_num }}</span>
                  <button class="quantity-btn" :class="{ disabled: scope.row.car_num >= 999 }" @click="handleIncrement(scope.row)">
                    + </button>
                  </div>
                </template>
              </el-table-column>

          <!-- 小计 -->
           <el-table-column 
           label="小计" 
            align="center"
          >
          <template #default="scope">
              ¥{{ (scope.row.goods_price * scope.row.car_num).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column 
            label="操作" 
            align="center"
          >
            <template #default="scope">
              <el-button 
                type="text" 
                text-color="#f56c6c"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 总计和结算 -->
        <div v-if="cartStore.cartList.length > 0" class="cart-summary">
          <div class="total-price">
            总计: 
            <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <el-button 
            type="primary" 
            size="large" 
            class="checkout-btn"
            @click="handleCheckout"
          >
            结算
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="Cart">
import { onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Header from '../components/Header.vue'
import useCartStore from '../store/cart'

const cartStore = useCartStore()

// 监听购物车列表，实时计算总计
const totalPrice = computed(() => {
  return cartStore.cartList.reduce((sum, item) => {
    return sum + item.goods_price * item.car_num;
  }, 0);
});

// 页面挂载时获取购物车数据
onMounted(() => {
  cartStore.getCartList();
});

// 减少数量
const handleDecrement = (row) => {
  if (row.car_num > 1) {
    row.car_num--;
  }
};

// 增加数量
const handleIncrement = (row) => {
  if (row.car_num < 999) {
    row.car_num++;
  }
};

// 删除商品
const handleDelete = async (productId) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？', 
    '提示', 
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const result = await cartStore.deleteFromCart(productId);
    if (result.success) {
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(result.message);
    }
  }).catch(() => {
  });
};

// 结算
const handleCheckout = () => {
  ElMessageBox.alert(
    '结算功能待实现，敬请期待~', 
    '提示', 
    {
      confirmButtonText: '确定'
    }
  );
};
</script>

<style scoped>
.cart-container {
  width: 100%;
  padding: 20px;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
}

.cart-card {
  max-width: 1200px;
  margin: 0 auto;
}

.cart-content {
  padding: 20px;
}

.cart-title {
  font-size: 22px;
  margin: 20px 0;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
}

.go-shopping-btn {
  margin-top: 20px;
}

.cart-table {
  margin: 20px 0;
}

/* 数量加减样式 */
.quantity-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity {
  margin: 0 10px;
  font-size: 14px;
}

/* 总计与结算 */
.cart-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.total-price {
  font-size: 18px;
  margin-right: 30px;
}

.price {
  color: #f56c6c;
  font-size: 22px;
  font-weight: bold;
}

.checkout-btn {
  background-color: #f56c6c;
  border: none;
  padding: 10px 30px;
}

.checkout-btn:hover {
  background-color: #e64949;
}
</style>